package cmu.mobile.lab;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;

public class SMSReceiver extends BroadcastReceiver {
	public static final String FASHIONISTA_MESSAGE_PREFIX = "You've received a new " +
							"Fashionista update. Open the Fashionista app " +
							"to check it out! ID:";
	public static final String SMS_RECEIVED = 
		"android.provider.Telephony.SMS_RECEIVED";
	public static final String FASHIONISTA_UPDATE = 
		"cmu.mobile.lab.fashionista.FASHIONISTA_UPDATE";
	
	@Override
	public void onReceive(Context context, Intent intent) {
		if (intent.getAction().equals(SMS_RECEIVED)) {
			Bundle bundle = intent.getExtras();
			SmsManager smsManager = SmsManager.getDefault();
			
			// Get text message data (so that you have a number to reply to)
			Object[] pdus = (Object[]) bundle.get("pdus");
			for (int i=0; i<pdus.length; i++) {
				SmsMessage message = SmsMessage.createFromPdu((byte[]) 
						pdus[i]);
				if (message.getMessageBody().startsWith(FASHIONISTA_MESSAGE_PREFIX)) {
					String id = message.getMessageBody().substring(
							FASHIONISTA_MESSAGE_PREFIX.length());
					Intent itemIntent = new Intent(FASHIONISTA_UPDATE);
					itemIntent.putExtra("itemid", id);
					context.sendBroadcast(itemIntent);
//					MMSContent newItem = ImageLoader.downloadItem(id);
//					Database database = new Database(context);
//	        		database.open();
//	        		database.addItem(newItem);
//	        		database.close();
	        		
				}
			}
			
		}
		
	}
}
